/**
 * @file log.c
 * @author chushang (email:chushangcs@163.com)
 * @brief  串口日志打印模块
 * @version 0.1
 * @date 2025-08-12
 *
 * @copyright Copyright (c) 2025
 *
 */

#include "log_usart.h"
#include "stdint.h"
#include <stdarg.h>
#include <stdio.h>

// 全局日志等级设置（可根据需要调整）
static LogLevel global_log_level = LOG_LEVEL_INFO;

/**
 * @brief   串口打印函数，调用者需要修改为实际串口发送函数
 *
 * @param[in] str  要发送的数据指针
 */
static void UART_SendString(const char *str)
{
    int len = 0;
    while (str[len] != 0)
    {
#error add uart transmit function here
        len++;
    }
}

void Log_Print(LogLevel level, const char *func, int line, const char *format, ...)
{
    // 检查日志等级是否启用
    if (level > global_log_level)
        return;

    // 添加等级前缀
    const char *prefix = "";
    switch (level)
    {
    case LOG_LEVEL_ERROR:
        prefix = "[ERROR]";
        break;
    case LOG_LEVEL_WARNING:
        prefix = "[WARN] ";
        break;
    case LOG_LEVEL_INFO:
        prefix = "[INFO] ";
        break;
    case LOG_LEVEL_DEBUG:
        prefix = "[DEBUG]";
        break;
    }

    // 输出前缀+函数名+行号
    char header[64]; // 存储函数名和行号的缓冲区
    snprintf(header, sizeof(header), "%s %s:%d > ", prefix, func, line);
    UART_SendString(header);

    // 处理可变参数
    va_list args;
    va_start(args, format);

    // 实际日志内容输出
    char buffer[128]; // 根据系统调整缓冲区大小
    vsnprintf(buffer, sizeof(buffer), format, args);
    UART_SendString(buffer); // 替换为实际的串口输出函数

    va_end(args);

    // 添加换行符
    UART_SendString("\r\n");
}

void Float2Str(char *str, float va)
{
    int flag = va < 0;
    int head = (int)va;
    int point = (int)((va - head) * 1000);
    head = abs(head);
    point = abs(point);
    if (flag)
        sprintf(str, "-%d.%d", head, point);
    else
        sprintf(str, "%d.%d", head, point);
}
